package com.xjh.him.interceptor;

import com.xjh.him.annotation.LoginVerify;
import com.xjh.him.common.LoginUser;
import com.xjh.him.constant.Constant;
import com.xjh.him.dao.UserMapper;
import com.xjh.him.domain.UserDO;
import com.xjh.him.util.JSONUtil;
import com.xjh.him.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import org.xjh.tool.Checks;
import org.xjh.tool.vo.AjaxResultVO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof ResourceHttpRequestHandler) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (!method.isAnnotationPresent(LoginVerify.class)) {
            return true;
        }
        String token = request.getHeader(Constant.AUTH_FIELD_NAME);
        if (Checks.isEmpty(token)) {
            AjaxResultVO resultVO = AjaxResultVO.getFailureResult("请先登录");
            writeResponse(response, resultVO);
            return false;
        }
        try {
            Long userId = JwtUtil.decodeUserId(token);
            UserDO userDO = userMapper.selectById(userId);
            LoginUser.setRequest(request, userDO);
        }catch (Exception e) {
            AjaxResultVO resultVO = AjaxResultVO.getFailureResult("会话过期，请重新登录");
            writeResponse(response, resultVO);
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUser.clear();
    }

    public void writeResponse(HttpServletResponse response, AjaxResultVO resultVO) throws IOException {
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        response.setContentType(Constant.DEFAULT_CONTENT_TYPE);
        PrintWriter writer = response.getWriter();
        writer.write(JSONUtil.toJSONStringWithNull(resultVO));
        writer.close();
    }
}
